package com.hqyj.aop;

import com.hqyj.anno.UserActionType;
import com.hqyj.dao.LogInfoMapper;
import com.hqyj.pojo.LogInfo;
import com.hqyj.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Component
public class LogAop {


    @Autowired
    LogInfoMapper logInfoMapper;



    @Pointcut("execution(* com.hqyj.controller.*.*(..))")
    public void pointCut(){

    }

    @After("pointCut()")
    public void logInfo(JoinPoint joinPoint){


        String className = joinPoint.getTarget().getClass().getName();
        try {
            Class<?> c = Class.forName(className);
            Method[] methods = c.getDeclaredMethods();
            String joinMethod = joinPoint.getSignature().getName();
            String TYPE = null;
            String ACTION = null;
            for (Method method : methods) {
                if (method.getName().equals(joinMethod)){
                    UserActionType annotation = method.getAnnotation(UserActionType.class);
                    if (annotation!= null){
                        TYPE = method.getAnnotation(UserActionType.class).Ltype();
                        ACTION = method.getAnnotation(UserActionType.class).desc();
                    }

                }
            }
            System.out.println("TYPE="+TYPE);
            System.out.println("ACTION="+ACTION);
            //获取系统当期时间
            Date date = new Date();
            System.out.println("当前时间"+date);
            //获取用户

            String user = (String) SecurityUtils.getSubject().getPrincipal();
//            String userName = user.getUserName();
            System.out.println("当前用户"+user);

            LogInfo logInfo = new LogInfo();
            logInfo.setLogAction(ACTION);
            logInfo.setLogTime(date);
            logInfo.setLogType(TYPE);
            logInfo.setLogUser(user);
            logInfoMapper.insert(logInfo);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}

